#!/bin/bash
NGINX_BIN="$(which nginx)"
NGINX_CONF="/etc/nginx/nginx.conf"
NGINX_VIP="192.168.33.16"
KEEPALIVED_CONF="/etc/keepalived/keepalived.conf"
#检测nginx可执行文件是否存在
if [ -z "$NGINX_BIN" ]; then exit 1; fi
#检测配置文件是否存在
if [ ! -s "$NGINX_CONF" ]; then exit 1; fi
#######################
#error code
#   1   null VIP
#   2   NGINX can not start
#
#########################

#获取keepalived 配置文件中的vip
function getVIP() {
    awk 'BEGIN{STATUS="STOP"}{if (match($0,/}/)){STATUS="STOP"};if (STATUS=="RECORD"){print $0};if (match($0,/virtual_ipaddress/)){STATUS="RECORD"}}' \
        KEEPALIVED_CONF
}

function Check() {
    function checkVIP() {
        if [ -z "$(ip addr | grep $NGINX_VIP)"]; then
            return 1
        else
            return 0
        fi
    }
    function CheckNGINX() {
        if [ 0 -eq $(ps -C nginx --no-headers | wc -l) ]; then
            NGINX_BIN -c "$NGINX_CONF" || return 2
        else
            return 0
        fi
    }
    if checkVIP ;then
    echo "VIP OK"
    elif
    echo "VIP BAD"
    fi
}

function Start() {
    NGINX_BIN -t && NGINX_BIN -c "$NGINX_CONF"
    return $(check)
}

function Stop() {
    NGINX_BIN -s stop
}

case $1 in
"check")
    Check
    ;;
"start")
    Start
    ;;
"stop")
    Stop
    ;;
"")
NGINX_BIN -v
;;
*)
    NGINX_BIN $@
    ;;
esac
